package com.wechat.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import java.util.Date;

public class WechatUtil {

    private static final Logger logger = Logger.getLogger(WechatUtil.class);

    /*appId*/
//    private static String appID = "wxef2bc7deed36d1b7";
//    /*appSecret*/
//    private static String appSecret = "6bbcd1bc458129a4c525fe6969a2d5ae";
    private static String appID = "wx2460d7e7cd668c34";
    /*appSecret*/
    private static String appSecret = "33862a66dddbf3968ba82c2a032cba14";
    /*接口请求accessToken*/
    private static String accessToken;
    /*accessToken失效时间*/
    private static Long expiresTime;
    /*网页授权accessToken*/
    private static String webOAuthAccessToken;
    /*网页授权返回的刷新token*/
    private static String webOAuthRefreshToken;
    /*openid;*/
    private static String openid;
    /*得到accessToken的请求url*/
    private final static String GET_ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
    /*创建菜单url*/
    private final static String CREATE_MENU_URL = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN";
    /*删除菜单url*/
    private final static String DELETE_MENU_URL = "https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=ACCESS_TOKEN";
    /*得到网页授权accessToken的url*/
    private final static String WEBOTUTH_GET_ACCESS_TOKEN_URL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
    /*网页授权时判断accessToken是否过期的url*/
    private final static String WEBOAUTH_REFRESH_TOKEN_URL = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=APPID&grant_type=refresh_token&refresh_token=REFRESH_TOKEN";
    /*得到用户信息url*/
    private final static String GET_USERINFO_URL = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";


    public static String getAccessToken(){
        try {
            if(accessToken == null || new Date().getTime() > expiresTime){
                String ret = HttpClient4Util.Get(GET_ACCESS_TOKEN_URL.replace("APPID",appID).replace("APPSECRET",appSecret));
                JSONObject myJson = JSONObject.parseObject(ret);
                accessToken = myJson.getString("access_token");
                Long expires_in = myJson.getLong("expires_in");
                expiresTime = new Date().getTime() + ((expires_in - 60) * 1000);    //尽量提前判断是否失效（这里是提前一分钟判断是否失效）
            }

        }catch (Exception e){
            logger.info(e.getMessage());
        }
        return accessToken;
    }

    public static void createMenu(String json) {
        /*先获取accessToken*/
        getAccessToken();

        try {
            HttpClient4Util.doPost(CREATE_MENU_URL.replace("ACCESS_TOKEN",accessToken),json);
        }catch (Exception e){
            logger.info(e.getMessage());
        }

    }


    public static void deleteMenu(){
        /*先获取accessToken*/
        getAccessToken();

        try {
            HttpClient4Util.Get(DELETE_MENU_URL.replace("ACCESS_TOKEN",accessToken));
        }catch (Exception e){
            logger.info(e.getMessage());
        }
    }


    /*通过code得到网页授权access_token*/
    public static String getWebOAuthAccessToken(String code) {
        String url = WEBOTUTH_GET_ACCESS_TOKEN_URL.replace("APPID", appID).replace("SECRET", appSecret).replace("CODE", code);
        String ret = "";
        try {
            ret =  HttpClient4Util.Get(url);
            JSONObject myJson = JSONObject.parseObject(ret);
            webOAuthAccessToken = (String) myJson.get("access_token");
            webOAuthRefreshToken = (String) myJson.get("refresh_token");
            openid = (String) myJson.get("openid");
        } catch (Exception e) {
            ret =  null;
        }

        return webOAuthAccessToken;
    }

    /*获取第二步的refresh_token后，请求以下链接获取access_token：*/
    public static Integer getWebOAuthRefreshToken(String code,String _reToken) {

        if(StringUtils.isBlank(_reToken)){
            getWebOAuthAccessToken(code);
        }
        getWebOAuthAccessToken(code);
        String url = WEBOAUTH_REFRESH_TOKEN_URL.replace("APPID", appID).replace("REFRESH_TOKEN",webOAuthRefreshToken);

        String ret = "";
        Integer result = 0;
        try {
            ret =  HttpClient4Util.Get(url);

            JSONObject myJson = JSONObject.parseObject(ret);
            String _accessToken = (String) myJson.get("access_token");
            String _refreshToken = (String) myJson.get("refresh_token");

            if(_accessToken.equals(webOAuthAccessToken)){
                result = 0;            //0不需要刷新
            }else {
                result = 1;            //1需要刷新
            }
        } catch (Exception e) {
            ret =  null;
        }

        return result;
    }

    public static String getUserInfo(){
        String result = "";
        try {
            result = HttpClient4Util.Get(GET_USERINFO_URL.replace("ACCESS_TOKEN",webOAuthAccessToken).replace("OPENID",openid));
        }catch (Exception e){
            logger.info(e.getMessage());
        }
        return result;
    }

    public static String getRefreshToken(){
        return webOAuthRefreshToken;
    }
}
